import { _decorator, Collider2D, Component, Contact2DType, instantiate, IPhysics2DContact, Node, Prefab } from 'cc';
import { GameManager } from '../GameManager';
const { ccclass, property } = _decorator;

@ccclass('HreoService')
export class HreoService extends Component {

    @property({type: Prefab})
    public hreoPrefab: Prefab|null = null;

    start() {
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onCollisionEnter, this);
            // collider.on(Contact2DType.END_CONTACT, this.onCollisionEnd, this);
        }
    }
    // 碰撞检测回调
    onCollisionEnter(selfCollider: Collider2D, other: Collider2D, contact: IPhysics2DContact | null) {
        // console.log('碰撞的对象:' , selfCollider.node.name, other.node.name);
        // 敌人
        if(other.tag < 10){
            // GameManager.Instance.genSpark(other.node)
        }
         // 实现道具技能
        if(other.tag == 1001 || other.tag == 1002 || other.tag == 1003){
            this.addBody(other.tag-1000)
            GameManager.Instance.delPrefab(other.node, 3)
        }

    }

    // 创建分身
    addBody(count: number){
        const size = this.node.parent.children.length;
        if(count <= 0 || size+count > 10)return;
        let newfab = null;
        // 计算旋转角度
        let rotation = 0;
        let addRotation = 360/(size+count);
        for (let i = 0; i < count; i++) { 
            newfab = instantiate(this.hreoPrefab)
            newfab.parent = this.node.parent
        }
        this.node.parent.children.forEach(ch => {
            // 重新设置每个子元素的旋转角度
            rotation = rotation + addRotation;
            ch.angle = rotation;
        })
    }

    // 监听回传
    toGenSpark(node: Node) {
        this.node.emit('genSpark', node);
    }

    update(deltaTime: number) {
        
    }
}

